package com.example.springboot3.filter;

import com.example.springboot3.pojo.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author 张琪
 * @date 2024-02-22 15:58
 */
public class LoginFilter extends OncePerRequestFilter {

    private static Set<String> whiteList =  new HashSet<>();

    static {
        whiteList.add("/login");
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果是白名单中的请求，直接放行
        if (whiteList.contains(request.getRequestURI())){
            filterChain.doFilter(request, response);
            return;
        }

        // 如果是其他请求，判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (Objects.nonNull(user)){
            filterChain.doFilter(request, response);
            return;
        }

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("请先登录");
        out.flush();
        out.close();
    }
}
